﻿using AMC.SubstitutionCache.Events;
using AMC.SubstitutionCache.Services;

using Orchard.DisplayManagement;

namespace AMC.SubstitutionCache.Handlers
{
    public class DefaultSubstitutionEventHandler : SubstitutionEvents
    {
        private readonly ISubstitutionSettings _settings;

        public DefaultSubstitutionEventHandler(ISubstitutionSettings settings)
        {
            _settings = settings;
        }

        public override void SubstitutionAdding(SubstitutionAddingContext context)
        {
            var shape = context.Shape;
            var shapeType = context.SubstitutionContext.ShapeType;

            if (((dynamic)shape).Cache == false || _settings.ExcludedShapeTypes.Contains(shapeType) || ParentHasContext(shape))
            {
                context.ShouldAdd = false;
                return;
            }
                

            // handle placeholders
            if (shapeType == "SubstitutionPlaceholder")
            {
                // we should have a replacement context already set
                // if we do, replace the one in the context with the one we saved
                var ctx = shape.GetSubstitutionContext();

                if (ctx != null)
                {
                    context.SubstitutionContext = ctx;
                    context.ShouldAdd = true;
                }    
            }  
        }

        private static bool ParentHasContext(IShape shape)
        {
            var parent = ((dynamic)shape).Parent as IShape;

            if (parent != null && parent.GetSubstitutionContext() != null)
                return true;

            return false;
        }
    }
}